# vowei.py - vowei integration for svn
#
# copyright 2010 Shi Yimin <yimin_shi@hotmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License versoin 2 or any later version
import urllib, urlparse, json, re, httplib

class vowei_hook_base(object):    
    _defaultbug_re = (r'#(\d+)')
    bug_re = re.compile(_defaultbug_re, re.IGNORECASE)
    bDebug = True

    def __init__(self):
        self.read_config()

    def debug_print(self, message):
        if ( self.bDebug ):
		f = open('vowei_hook.log', 'a')
		f.write(message)
		f.write('\n')
		f.close

    def read_config(self):
        pass

    def configitems(self, section):
        pass
            
    def find_work_item_ids(self, message):
        start = 0
        ids = set()
        while True:
            m = self.bug_re.search(message, start)
            if not m:
                break
            start = m.end()
            ids.add(int(m.group(1)))            
        return ids
            
    def map_committer(self, user):
        '''map name of committer to vowei user name.'''
        for committer, bzuser in configitems('usermap'):
            if committer.lower() == user.lower():
                return bzuser
        return user

    def get_vowei_user(self, committer):
        '''see if committer is a registered vowei user. Return
        vowei username and userid if so. If not, return default
        vowei username and userid.'''
        user = self.map_committer(committer)
        try:
            userid = self.get_user_id(user)
        except KeyError:
            raise util.Abort(_('cannot find vowei user id for %s or %s') %
                             (user, defaultuser))
        return (user, userid)

    def create_comments(self, description, comiter, changeid, ids):
        comments = []
        user = self.get_vowei_user(commiter)
        
        for id in ids:
            message = ('Change set %s is made for work item %d. \n \
                        --------------------------------------------\n \
                        %s') % (changeid, id, description)
            
            comments.append({
                'PostId': id,
                'PostType': 'Ticket',
                'Text': message,
                'User': user
            })

        return comments

    def post_comments(self, comments, host, path):    
        http_body = json.dumps(comments)
        headers = {"Content-type": "application/json",
                   "Accept": "text/plain"}

        conn = httplib.HTTPConnection(host)
        conn.request("POST", path, http_body, headers)
        conn.close()
